package cn.org.channl.server.handler;

import cn.org.channl.message.Message;
import cn.org.channl.message.Static;
import cn.org.channl.exception.ValidateCKException;
import cn.org.channl.server.action.ChannelActionAdapter;
import cn.org.channl.server.action.LoginAction;
import cn.org.channl.session.ConnectorManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.handler.timeout.IdleStateEvent;


import lombok.extern.slf4j.Slf4j;

/**
 * @author
 *
 */
@Slf4j
@Sharable
public class BusinessHandler extends SimpleChannelInboundHandler<Message> {
	/**
	 * 真正的业务逻辑处理,责任转到具体的action上处理
	 */
	private ChannelActionAdapter abstractAction;

	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		log.info("client address {} on line",ctx.channel().remoteAddress());//设备上线
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) {
		log.info("client address{} off line",ctx.channel().remoteAddress());//设备离线
		ConnectorManager.connectorManager.remove(ctx.channel());
	}

	@Override
	protected void channelRead0(ChannelHandlerContext chc, Message message) {
		byte messageId = message.getMessageId();
		byte[] payload = message.getPayload();

		String a = String.valueOf(messageId);
		log.info("messageId=============="+a);
		switch(messageId){
			case Static.MESSAGE_ID_LNK_LIN:
				//do something ...
				abstractAction = new LoginAction(chc,message);
				break;
		}
		abstractAction.execute();
	}

	/**
	 * 这里有个ValidateCKException需要处理,异常日志处理
	 * 
	 */
	@SuppressWarnings("unused")
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
		if(cause instanceof ValidateCKException){
			ValidateCKException validateCKException = (ValidateCKException)cause;
			Channel channel = validateCKException.getChannel();
			Message message = validateCKException.getMsg();
			ctx.close();
		}
		
	}

	/**
	 * allIdle状态,把Channel从ConnectorManager踢出去
	 */
	@SuppressWarnings("unused")
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)throws Exception {
		if(evt instanceof IdleStateEvent){
			IdleStateEvent idleStateEvent = (IdleStateEvent)evt;
		}
		
		super.userEventTriggered(ctx, evt);
	}
}
